package com.baizhi.springboot.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class CacheAspect {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 连接点
     * @param joinPoint
     * @return
     */
    @Around("@annotation(com.baizhi.springboot.annotation.CacheUsing)")
    public Object around(ProceedingJoinPoint joinPoint) {
        //获得目标类名
        String key = joinPoint.getTarget().getClass().getName();
        //获得目标方法名
        String name = joinPoint.getSignature().getName();
        //获得目标方法带的参数
        Object[] args = joinPoint.getArgs();
        StringBuffer stringBuffer = new StringBuffer(name);
        for (Object arg : args) {
            stringBuffer.append(arg);
        }
        String field = stringBuffer.toString();
        HashOperations hashOperations = redisTemplate.opsForHash();
        Object value = hashOperations.get(key, field);
        if (value != null) {
            return value;
        }

        try {
            //放行返回结果
            Object result = joinPoint.proceed();
            hashOperations.put(key,field,result);
            System.out.println(result+"**********");
            return result;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            throw new RuntimeException("有异常");
        }

    }

    @After("@annotation(com.baizhi.springboot.annotation.CacheClear)")
    public void after(JoinPoint joinPoint) {
        String key = joinPoint.getTarget().getClass().getName();
        redisTemplate.delete(key);
    }
}
